import axios from 'axios' // 导入axios
import { loginUrl } from '@/constants'
import qs from 'qs'
import { removeToken } from '@/libs/util.auth'
import { Message, MessageBox } from 'element-ui'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.NODE_ENV === 'development' ? '' : '/', // api 的 base_url
  timeout: 300000, // 请求连接超时,
})
// request interceptor
service.interceptors.request.use(
  config => {
    if (config.url) {
      if (config.headers['Content-Type'] && config.headers['Content-Type'] == 'application/x-www-form-urlencoded') {
        config.data = qs.stringify(config.data);
      }
      config.url = config.url + (config.url.indexOf('?') > 0 ? '&' : '?') + `cb = ${new Date().getTime()}`
    }
    return config
  },
  error => {
    // Do something with request error
    return Promise.reject(error)
  }
)
// response interceptor
service.interceptors.response.use(
  response => {
    if (response.status !== 200) {
      if (response.status === 21315) { // 这里根据自己的连接超时的具体编码进行处理
        const timeoutflag = null
        removeToken('uc_token')
        if (timeoutflag !== null) {
          clearTimeout(timeoutflag)
        } else {
          Message({
            showClose: true,
            message: '登录超时，请重新登录',
            iconClass: 'el-icon-circle-close',
            customClass: 'el-message--error'
          })
        }
        window.location.href = loginUrl;
      } else if (response.status === 1) {
        const timeoutflag = null
        if (timeoutflag !== null) {
          clearTimeout(timeoutflag)
        } else {
          Message({
            showClose: true,
            message: response.data.msg,
            iconClass: 'el-icon-circle-close',
            customClass: 'el-message--error'
          })
        }
      }
    } else {
      if (!response.data.success) {
        MessageBox.alert(response.data.msg, '提示', {
          confirmButtonText: '确定',
          callback: () => {
            removeToken('uc_token')
            window.location.href = loginUrl;
          }
        });
      } else {
        return response.data
      }
    }
  },
  error => {
    return Promise.reject(error) // 在这对响应错误做统一处理
  }
)

export default service
